<template>
  <div style="margin-top: 50px">
    <el-form :model="value" :rules="rules" ref="productInfoForm" label-width="120px" class="form-inner-container" size="small">
      <el-form-item label="商品主图：">
        <multi-upload v-model="selectProductPics"></multi-upload>
      </el-form-item>
      <el-form-item label="商品分类：" prop="productCategoryId">
        <el-cascader
          v-model="selectProductCateValue"
          :options="productCateOptions"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="属性集合：">
        <el-input v-model="value.attributeSetNames"
                  placeholder="所选分类没有挂接属性集合" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="商品标题：" prop="name"  >
        <el-input v-model="value.name"
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 4}"
                  maxlength="60"
                  show-word-limit
                  placeholder="请输入商品标题(标题组成：商品描述+规格)"></el-input>
      </el-form-item>
      <el-form-item label="商品别名：">
        <el-input v-model="value.keywords" placeholder="别名用于搜索。多个逗号(,)分割"></el-input>
      </el-form-item>

      <el-form-item label="商品规格：">
        <el-row>
          <el-col :span="16"> <el-checkbox  v-model="value.buildProjectByModel" :key="value.buildProjectByModel" @change="clickBuildProjectByModelBox"><p style="color: #990055;font-size:12px;">按规格属性添加商品</p></el-checkbox></el-col>
        </el-row>
        <el-card shadow="never"  v-if="value.buildProjectByModel" class="cardBg">
          <div v-for="(productAttr,idx) in productModelAttrList">
            <el-row>
              <el-col :span="16"> {{productAttr.name}}：<el-checkbox  v-model="productAttr.addPicture" :key="productAttr.addPicture" @change="clickAddPictureBox(idx)"><p style="color: #8b8b8b;font-size:12px;">添加图片</p></el-checkbox></el-col>
            </el-row>
            <el-checkbox-group v-if="productAttr.handAddStatus===0" v-model="productModelAttrList[idx].values">
              <el-checkbox v-for="item in getInputListArr(productAttr.inputList)" :label="item" :key="item"
                           class="littleMarginLeft"></el-checkbox>
            </el-checkbox-group>
            <div v-else>
              <el-checkbox-group v-model="productModelAttrList[idx].values">
                <div v-for="(item,index) in productModelAttrList[idx].options" style="display: inline-block"
                     class="littleMarginLeft">
                  <el-checkbox :label="item" :key="item"></el-checkbox>
                  <el-button type="text" class="littleMarginLeft" @click="handleRemoveProductAttrValue(idx,index)">删除
                  </el-button>
                </div>
              </el-checkbox-group>
              <el-input v-model="addProductAttrValue" style="width: 160px;margin-left: 10px" clearable></el-input>
              <el-button class="littleMarginLeft" @click="handleAddProductAttrValue(idx)">增加</el-button>
            </div>
          </div>
        </el-card>
        <el-table v-if="value.buildProjectByModel"  style="width: 100%;margin-top: 20px"
                  :data="value.skuStockList"
                  border>
          <el-table-column
            v-for="(item,index) in productModelAttrList"
            :label="item.name"
            :key="item.id"
            align="center">
            <template slot-scope="scope">
              {{getProductSkuSp(scope.row,index)}}
            </template>
          </el-table-column>
          <el-table-column
            label="销售价格"
            width="100"
            align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.price"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="促销价格"
            width="100"
            align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.promotionPrice"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="商品库存"
            width="80"
            align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.stock"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="库存预警值"
            width="80"
            align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.lowStock"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="SKU编号"
            width="160"
            align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.skuCode"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="80"
            align="center">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="handleRemoveProductSku(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button v-if="value.buildProjectByModel"
                   type="primary"
          style="margin-top: 30px"
          @click="handleRefreshProductSkuList">规格属性变更，重新创建sku列表
        </el-button>
      </el-form-item>
      <el-form-item label="属性图片：" v-if="hasAttrPic">
        <el-card shadow="never" class="cardBg">
          <div v-for="(item,index) in selectProductAttrPics">
            <span>{{item.name}}:</span>
            <single-upload v-model="item.pic"
                           style="width: 300px;display: inline-block;margin-left: 10px"></single-upload>
          </div>
        </el-card>
      </el-form-item>
      <el-form-item label="商品售价￥：" prop="price" v-if="!value.buildProjectByModel"
                    :rules="{required: true, message: '商品售价不能为空', trigger: 'blur'}"
      >
        <el-input-number v-model="value.price"  controls-position="right" :step="0.1" :precision="1" :min="0" :max="9999999"></el-input-number>
      </el-form-item>
      <el-form-item label="商品库存：" prop="stock" v-if="!value.buildProjectByModel"
                    :rules="{required: true, message: '商品库存不能为空', trigger: 'blur'}"
      >
        <el-input-number v-model="value.stock"  controls-position="right" :step="1"  :min="0" :max="9999999"></el-input-number>
      </el-form-item>
      <el-form-item label="商品属性：">
        <el-card shadow="never" class="cardBg">
          <div v-for="(item,index) in selectProductParam" :class="{littleMarginTop:index!==0}">
            <div class="paramInputLabel">{{item.name}}:</div>
            <el-select v-if="item.inputType===1" class="paramInput" v-model="selectProductParam[index].value">
              <el-option
                v-for="item in getParamInputList(item.inputList)"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            <el-input v-else class="paramInput" v-model="selectProductParam[index].value"></el-input>
          </div>
        </el-card>
      </el-form-item>
      <el-form-item label="商品详情：">
          <el-input v-model="value.detailHtml"
                    type="textarea"
                    :autosize="{ minRows: 6, maxRows: 20}"
                    maxlength="500"
                    show-word-limit
                    placeholder="请输入商品描述以提升转化(若未编辑，商品发布后轮播图将自动填充到图文详情)"></el-input>
          详情图：<multi-upload v-model="selectProductDetailPics" :maxCount="6"></multi-upload>
          详情底图：<multi-upload v-model="selectProductDetailBottomPics" :maxCount="1"></multi-upload>
      </el-form-item>
      <el-form-item label="服务保证：">
        <el-checkbox-group v-model="selectServiceList">
          <el-checkbox :label="1">无忧退货</el-checkbox>
          <el-checkbox :label="2">快速退款</el-checkbox>
          <el-checkbox :label="3">免费包邮</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button type="primary" size="medium" @click="handleNext('productInfoForm')">下一步，填写商品促销</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {fetchListWithChildren} from '@/api/productCate'
  import {fetchList as fetchBrandList} from '@/api/brand'
  import {fetchList as fetchProductAttrCateList} from '@/api/productAttrSet'
  import {listBySetId } from '@/api/productAttr'
  import {getProduct} from '@/api/product';
  import SingleUpload from '@/components/Upload/singleUpload'
  import MultiUpload from '@/components/Upload/multiUpload'
  import Tinymce from '@/components/Tinymce'
  import {listByCategoryId as listAttributeSetByCategoryId} from "@/api/productCategoryAttrCategoryMapping";

  export default {
    name: "ProductInfoDetail",
    components: {SingleUpload, MultiUpload, Tinymce},
    props: {
      value: Object,
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        hasEditCreated:false,
        //选中商品分类的值
        selectProductCateValue: [],
        productCateOptions: [],
        brandOptions: [],

        //商品属性相关--开始
        //商品属性集合下拉选项
        productAttributeCategoryOptions: [],
        //选中的商品属性
        productModelAttrList: [],
        addPictureAttributeIndex:null,
        //选中的商品参数
        selectProductParam: [],
        //选中的商品属性图片
        selectProductAttrPics: [],
        //可手动添加的商品属性
        addProductAttrValue: '',
        //商品富文本详情激活类型
        activeHtmlName: 'pc',
        //商品属性相关--结束

        rules: {
          name: [
            {required: true, message: '请输入商品名称', trigger: 'blur'},
            {min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur'}
          ],
         /* subTitle: [{required: true, message: '请输入商品副标题', trigger: 'blur'}],*/
          productCategoryId: [{required: true, message: '请选择商品分类', trigger: 'blur'}],
         /* brandId: [{required: true, message: '请选择商品品牌', trigger: 'blur'}],*/
          description: [{required: true, message: '请输入商品介绍', trigger: 'blur'}],
          requiredProp: [{required: true, message: '该项为必填项', trigger: 'blur'}]
        }
      };
    },
    created() {
      this.getProductCateList();
    },
    computed:{
      //商品的编号
      productId(){
        return this.value.id;
      },
      //是否有商品属性图片
      hasAttrPic() {
        if (this.selectProductAttrPics.length < 1) {
          return false;
        }
        return true;
      },
      //商品的主图和画册图片
      selectProductPics:{
        get:function () {
          let pics=[];
          if(this.value.pic===undefined||this.value.pic==null||this.value.pic===''){
            return pics;
          }
          pics.push(this.value.pic);
          if(this.value.albumPics===undefined||this.value.albumPics==null||this.value.albumPics===''){
            return pics;
          }
          let albumPics = this.value.albumPics.split(',');
          for(let i=0;i<albumPics.length;i++){
            if(albumPics[i] !== ''){
              pics.push(albumPics[i]);
            }
          }
          return pics;
        },
        set:function (newValue) {
          if (newValue == null || newValue.length === 0) {
            this.value.pic = null;
            this.value.albumPics = null;
          } else {
            this.value.pic = newValue[0];
            this.value.albumPics = '';
            if (newValue.length > 1) {
              for (let i = 1; i < newValue.length; i++) {
                this.value.albumPics += newValue[i];
                if (i !== newValue.length - 1) {
                  this.value.albumPics += ',';
                }
              }
            }
          }
        }
      },
      selectProductDetailPics:{
        get:function () {
          let pics=[];
          if(this.value.detailPic===undefined||this.value.detailPic==null||this.value.detailPic===''){
            return pics;
          }
          pics.push(this.value.detailPic);
          let albumDetailPics = this.value.albumDetailPics.split(',');
          for(let i=0;i<albumDetailPics.length;i++){
            if(albumDetailPics[i] !== ''){
              pics.push(albumDetailPics[i]);
            }
          }
          return pics;
        },
        set:function (newValue) {
          if (newValue == null || newValue.length === 0) {
            this.value.detailPic = null;
            this.value.albumDetailPics = null;
          } else {
            this.value.detailPic = newValue[0];
            this.value.albumDetailPics = '';
            if (newValue.length > 1) {
              for (let i = 1; i < newValue.length; i++) {
                this.value.albumDetailPics += newValue[i];
                if (i !== newValue.length - 1) {
                  this.value.albumDetailPics += ',';
                }
              }
            }
          }
        }
      },
      selectProductDetailBottomPics:{
        get:function () {
          let pics=[];
          if(this.value.detailBottomPic===undefined||this.value.detailBottomPic==null||this.value.detailBottomPic===''){
            return pics;
          }
          pics.push(this.value.detailBottomPic);
          let albumDetailBottomPics = this.value.albumDetailBottomPics.split(',');
          for(let i=0;i<albumDetailBottomPics.length;i++){
            if(albumDetailBottomPics[i] !== ''){
              pics.push(albumDetailBottomPics[i]);
            }
          }
          return pics;
        },
        set:function (newValue) {
          if (newValue == null || newValue.length === 0) {
            this.value.detailBottomPic = null;
            this.value.albumDetailBottomPics = null;
          } else {
            this.value.detailBottomPic = newValue[0];
            this.value.albumDetailBottomPics = '';
            if (newValue.length > 1) {
              for (let i = 1; i < newValue.length; i++) {
                this.value.albumDetailBottomPics += newValue[i];
                if (i !== newValue.length - 1) {
                  this.value.albumDetailBottomPics += ',';
                }
              }
            }
          }
        }
      },
      //选中的服务保证
      selectServiceList: {
        get() {
          let list = [];
          if (this.value.serviceIds === undefined || this.value.serviceIds == null || this.value.serviceIds === '') return list;
          let ids = this.value.serviceIds.split(',');
          for (let i = 0; i < ids.length; i++) {
            list.push(Number(ids[i]));
          }
          return list;
        },
        set(newValue) {
          let serviceIds = '';
          if (newValue != null && newValue.length > 0) {
            for (let i = 0; i < newValue.length; i++) {
              serviceIds += newValue[i] + ',';
            }
            if (serviceIds.endsWith(',')) {
              serviceIds = serviceIds.substr(0, serviceIds.length - 1)
            }
            this.value.serviceIds = serviceIds;
          } else {
            this.value.serviceIds = null;
          }
        }
      }
    },
    watch: {

      productId:function(newValue){
        if(!this.isEdit)return;
        if(this.hasEditCreated)return;
        if(newValue===undefined||newValue==null||newValue===0)return;
        this.handleEditCreated();
      },
      //商品分类变化
      selectProductCateValue: function (newValue) {
        if (newValue != null && newValue.length === 2) {
          this.value.productCategoryId = newValue[1];
          this.value.productCategoryName= this.getCateNameById(this.value.productCategoryId);
        } else {
          this.value.productCategoryId = null;
          this.value.productCategoryName=null;
        }
        //属性集合重新查询
        this.getHaveMappingAttributeSetList();
        // 规格重新查询

        //基于规格的价格列表重新设置
      }
    },
    methods: {
      //点击属性列表右边的增加属性图片的checkbox按钮
      clickAddPictureBox(idx){
        let current  =this.productModelAttrList[idx];
        if(current.addPicture){
          for(let i=0;i<this.productModelAttrList.length;i++) {
            let item = this.productModelAttrList[i];
            if (item.addPicture && i != idx) {
              current.addPicture = false;
              this.$message({
                message: '只能有一个规格属性添加图片',
                type: 'warning',
                duration: 1000
              });
              break;
            }
          }
        }
        let addPictureIdx = null;
        for(let i=0;i<this.productModelAttrList.length;i++) {
          let item = this.productModelAttrList[i];
          if (item.addPicture) {
            addPictureIdx =i;
          }
        }
        if(addPictureIdx === 0 || addPictureIdx > 0){
          this.addPictureAttributeIndex = addPictureIdx;
        }else{
          this.addPictureAttributeIndex = null;
        }
      },
      //点击根据规格添加商品的按钮
      clickBuildProjectByModelBox(value){
        //暂时不做什么
      },
      handleEditCreated() {
        //根据商品属性集合id获取属性和参数
        if(this.value.attributeSetIdList!=null){
          this.handleProductAttrSetChange(this.value.attributeSetIdList);
        }
        if(this.value.productCategoryId!=null){
          this.selectProductCateValue.push(this.value.cateParentId);
          this.selectProductCateValue.push(this.value.productCategoryId);
        }
        this.hasEditCreated=true;
      },
      //处理编辑逻辑
      getProductCateList() {
        fetchListWithChildren().then(response => {
          let list = response.data;
          this.productCateOptions = [];
          for (let i = 0; i < list.length; i++) {
            let children = [];
            if (list[i].children != null && list[i].children.length > 0) {
              for (let j = 0; j < list[i].children.length; j++) {
                children.push({label: list[i].children[j].name, value: list[i].children[j].id});
              }
            }
            this.productCateOptions.push({label: list[i].name, value: list[i].id, children: children});
          }
        });
      },

      //获取已经映射的属性集合
      getHaveMappingAttributeSetList() {
        let listQuery={};
        if(this.value.productCategoryId && this.value.productCategoryId!=0){
          listQuery.categoryId=this.value.productCategoryId;
        }
        listAttributeSetByCategoryId(listQuery).then(response => {
          this.value.haveMappingAttributeSetList = response.data;
          this.value.attributeSetIdList =[];
          this.value.attributeSetNames ="";
          if(this.value.haveMappingAttributeSetList.length>0){
            this.value.haveMappingAttributeSetList.forEach(item=>{
              this.value.attributeSetIdList.push(item.id);
              this.value.attributeSetNames = this.value.attributeSetNames+","+item.name;
            });
            this.value.attributeSetNames =this.value.attributeSetNames.substring(1);
            //处理属性集合变化
            this.handleProductAttrSetChange(this.value.attributeSetIdList)
          }
        });
      },
      getBrandList() {
        fetchBrandList({pageNum: 1, pageSize: 100}).then(response => {
          this.brandOptions = [];
          let brandList = response.data.list;
          for (let i = 0; i < brandList.length; i++) {
            this.brandOptions.push({label: brandList[i].name, value: brandList[i].id});
          }
        });
      },
      getCateNameById(id){
        let name=null;
        for(let i=0;i<this.productCateOptions.length;i++){
          for(let j=0;j<this.productCateOptions[i].children.length;j++){
            if(this.productCateOptions[i].children[j].value===id){
              name=this.productCateOptions[i].children[j].label;
              return name;
            }
          }
        }
        return name;
      },

      handleBrandChange(val) {
        let brandName = '';
        for (let i = 0; i < this.brandOptions.length; i++) {
          if (this.brandOptions[i].value === val) {
            brandName = this.brandOptions[i].label;
            break;
          }
        }
        this.value.brandName = brandName;
      },
     /* getProductAttrCateList() {
        let param = {pageNum: 1, pageSize: 100};
        fetchProductAttrCateList(param).then(response => {
          this.productAttributeCategoryOptions = [];
          let list = response.data.list;
          for (let i = 0; i < list.length; i++) {
            this.productAttributeCategoryOptions.push({label: list[i].name, value: list[i].id});
          }
        });
      },*/
      getProductAttrList(type, setIdList) {
        let param = {
          pageNum: 1,
          pageSize: 200,
          type: type,
          setIdList: setIdList
        };

        listBySetId(param).then(response => {
          let list = response.data.list;
          if (type === 0) {
            this.productModelAttrList = [];
            for (let i = 0; i < list.length; i++) {
              let options = [];
              let values = [];
              if (this.isEdit) {
                if (list[i].handAddStatus === 1) {
                  //编辑状态下获取手动添加编辑属性
                  options = this.getEditAttrOptions(list[i].id);
                }
                //编辑状态下获取选中属性
                values = this.getEditAttrValues(i);
              }
              this.productModelAttrList.push({
                id: list[i].id,
                name: list[i].name,
                handAddStatus: list[i].handAddStatus,
                inputList: list[i].inputList,
                values: values,
                options: options,
                addPicture:false
              });
            }
            if(this.isEdit){
              //编辑模式下刷新商品属性图片
              this.refreshProductAttrPics();
            }
          } else {
            this.selectProductParam = [];
            for (let i = 0; i < list.length; i++) {
              let value=null;
              if(this.isEdit){
                //编辑模式下获取参数属性
                value= this.getEditParamValue(list[i].id);
              }
              this.selectProductParam.push({
                id: list[i].id,
                name: list[i].name,
                value: value,
                inputType: list[i].inputType,
                inputList: list[i].inputList
              });
            }
          }
        });
      },
      //获取设置的可手动添加属性值
      getEditAttrOptions(id) {
        let options = [];
        for (let i = 0; i < this.value.productAttributeValueList.length; i++) {
          let attrValue = this.value.productAttributeValueList[i];
          if (attrValue.productAttributeId === id) {
            let strArr = attrValue.value.split(',');
            for (let j = 0; j < strArr.length; j++) {
              options.push(strArr[j]);
            }
            break;
          }
        }
        return options;
      },
      //获取选中的属性值
      getEditAttrValues(index) {
        let values = new Set();
        if (index === 0) {
          for (let i = 0; i < this.value.skuStockList.length; i++) {
            let sku = this.value.skuStockList[i];
            let spData = JSON.parse(sku.spData);
            if (spData!= null && spData.length>=1) {
              values.add(spData[0].value);
            }
          }
        } else if (index === 1) {
          for (let i = 0; i < this.value.skuStockList.length; i++) {
            let sku = this.value.skuStockList[i];
            let spData = JSON.parse(sku.spData);
            if (spData!= null && spData.length>=2) {
              values.add(spData[1].value);
            }
          }
        } else {
          for (let i = 0; i < this.value.skuStockList.length; i++) {
            let sku = this.value.skuStockList[i];
            let spData = JSON.parse(sku.spData);
            if (spData!= null && spData.length>=3) {
              values.add(spData[2].value);
            }
          }
        }
        return Array.from(values);
      },
      //获取属性的值
      getEditParamValue(id){
        for(let i=0;i<this.value.productAttributeValueList.length;i++){
          if(id===this.value.productAttributeValueList[i].productAttributeId){
            return this.value.productAttributeValueList[i].value;
          }
        }
      },

      //属性分类改变
      handleProductAttrSetChange(setIdList) {
        this.getProductAttrList(0, setIdList);
        this.getProductAttrList(1, setIdList);
      },
      getInputListArr(inputList) {
        return inputList.split(',');
      },
      handleAddProductAttrValue(idx) {
        let options = this.productModelAttrList[idx].options;
        if (this.addProductAttrValue == null || this.addProductAttrValue == '') {
          this.$message({
            message: '属性值不能为空',
            type: 'warning',
            duration: 1000
          });
          return
        }
        if (options.indexOf(this.addProductAttrValue) !== -1) {
          this.$message({
            message: '属性值不能重复',
            type: 'warning',
            duration: 1000
          });
          return;
        }
        this.productModelAttrList[idx].options.push(this.addProductAttrValue);
        this.addProductAttrValue = null;
      },
      handleRemoveProductAttrValue(idx, index) {
        this.productModelAttrList[idx].options.splice(index, 1);
      },
      getProductSkuSp(row, index) {
        let spData = JSON.parse(row.spData);
        if(spData!=null&&index<spData.length){
          return spData[index].value;
        }else{
          return null;
        }
      },
      handleRefreshProductSkuList() {
        this.$confirm('刷新列表将导致sku信息重新生成，是否要刷新', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.refreshProductAttrPics();
          this.refreshProductSkuList();
        });
      },
      handleSyncProductSkuPrice(){
        this.$confirm('将同步第一个sku的价格到所有sku,是否继续', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if(this.value.skuStockList!==null&&this.value.skuStockList.length>0){
            let tempSkuList = [];
            tempSkuList = tempSkuList.concat(tempSkuList,this.value.skuStockList);
            let price=this.value.skuStockList[0].price;
            for(let i=0;i<tempSkuList.length;i++){
              tempSkuList[i].price=price;
            }
            this.value.skuStockList=[];
            this.value.skuStockList=this.value.skuStockList.concat(this.value.skuStockList,tempSkuList);
          }
        });
      },
      handleSyncProductSkuStock(){
        this.$confirm('将同步第一个sku的库存到所有sku,是否继续', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if(this.value.skuStockList!==null&&this.value.skuStockList.length>0){
            let tempSkuList = [];
            tempSkuList = tempSkuList.concat(tempSkuList,this.value.skuStockList);
            let stock=this.value.skuStockList[0].stock;
            let lowStock=this.value.skuStockList[0].lowStock;
            for(let i=0;i<tempSkuList.length;i++){
              tempSkuList[i].stock=stock;
              tempSkuList[i].lowStock=lowStock;
            }
            this.value.skuStockList=[];
            this.value.skuStockList=this.value.skuStockList.concat(this.value.skuStockList,tempSkuList);
          }
        });
      },
      refreshProductSkuList() {
        this.value.skuStockList = [];
        let skuList = this.value.skuStockList;
        //只有一个属性时
        if (this.productModelAttrList.length === 1) {
          let attr = this.productModelAttrList[0];
          for (let i = 0; i < attr.values.length; i++) {
            skuList.push({
              spData: JSON.stringify([{key:attr.name,value:attr.values[i]}])
            });
          }
        } else if (this.productModelAttrList.length === 2) {
          let attr0 = this.productModelAttrList[0];
          let attr1 = this.productModelAttrList[1];
          for (let i = 0; i < attr0.values.length; i++) {
            if (attr1.values.length === 0) {
              skuList.push({
                spData: JSON.stringify([{key:attr0.name,value:attr0.values[i]}])
              });
              continue;
            }
            for (let j = 0; j < attr1.values.length; j++) {
              let spData = [];
              spData.push({key:attr0.name,value:attr0.values[i]});
              spData.push({key:attr1.name,value:attr1.values[j]});
              skuList.push({
                spData: JSON.stringify(spData)
              });
            }
          }
        } else {
          let attr0 = this.productModelAttrList[0];
          let attr1 = this.productModelAttrList[1];
          let attr2 = this.productModelAttrList[2];
          for (let i = 0; i < attr0.values.length; i++) {
            if (attr1.values.length === 0) {
              skuList.push({
                spData: JSON.stringify([{key:attr0.name,value:attr0.values[i]}])
              });
              continue;
            }
            for (let j = 0; j < attr1.values.length; j++) {
              if (attr2.values.length === 0) {
                let spData = [];
                spData.push({key:attr0.name,value:attr0.values[i]});
                spData.push({key:attr1.name,value:attr1.values[j]});
                skuList.push({
                  spData: JSON.stringify(spData)
                });
                continue;
              }
              for (let k = 0; k < attr2.values.length; k++) {
                let spData = [];
                spData.push({key:attr0.name,value:attr0.values[i]});
                spData.push({key:attr1.name,value:attr1.values[j]});
                spData.push({key:attr2.name,value:attr2.values[k]});
                skuList.push({
                  spData: JSON.stringify(spData)
                });
              }
            }
          }
        }
      },
      //产品的某一个可以添加图片的属性选中值列出图片添加列表
      refreshProductAttrPics() {
        this.selectProductAttrPics = [];
        if (this.productModelAttrList.length >= 1 && (this.addPictureAttributeIndex===0 || this.addPictureAttributeIndex > 0 )) {
          let values = this.productModelAttrList[this.addPictureAttributeIndex].values;
          for (let i = 0; i < values.length; i++) {
            let pic=null;
            if(this.isEdit){
              //编辑状态下获取图片
              pic=this.getProductSkuPic(values[i]);
            }
            this.selectProductAttrPics.push({name: values[i], pic: pic})
          }
        }
      },
      //获取商品相关属性的图片
      getProductSkuPic(name){
        for(let i=0;i<this.value.skuStockList.length;i++){
          let spData = JSON.parse(this.value.skuStockList[i].spData);
          if(name===spData[0].value){
            return this.value.skuStockList[i].pic;
          }
        }
        return null;
      },
      //合并商品属性
      mergeProductAttrValue() {
        this.value.productAttributeValueList = [];
        for (let i = 0; i < this.productModelAttrList.length; i++) {
          let attr = this.productModelAttrList[i];
          if (attr.handAddStatus === 1 && attr.options != null && attr.options.length > 0) {
            this.value.productAttributeValueList.push({
              productAttributeId: attr.id,
              value: this.getOptionStr(attr.options)
            });
          }
        }
        for (let i = 0; i < this.selectProductParam.length; i++) {
          let param = this.selectProductParam[i];
          this.value.productAttributeValueList.push({
            productAttributeId: param.id,
            value: param.value
          });
        }
      },
      //合并商品属性图片
      mergeProductAttrPics() {
        for (let i = 0; i < this.selectProductAttrPics.length; i++) {
          for (let j = 0; j < this.value.skuStockList.length; j++) {
            let spData = JSON.parse(this.value.skuStockList[j].spData);
            if (spData[0].value === this.selectProductAttrPics[i].name) {
              this.value.skuStockList[j].pic = this.selectProductAttrPics[i].pic;
            }
          }
        }
      },
      getOptionStr(arr) {
        let str = '';
        for (let i = 0; i < arr.length; i++) {
          str += arr[i];
          if (i != arr.length - 1) {
            str += ',';
          }
        }
        return str;
      },
      handleRemoveProductSku(index, row) {
        let list = this.value.skuStockList;
        if (list.length === 1) {
          list.pop();
        } else {
          list.splice(index, 1);
        }
      },
      getParamInputList(inputList) {
        return inputList.split(',');
      },
      handlePrev() {
        this.$emit('prevStep')
      },
      handleNext() {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$emit('nextStep');
          } else {
            this.$message({
              message: '验证失败',
              type: 'error',
              duration:1000
            });
            return false;
          }
        });
        this.mergeProductAttrValue();
        this.mergeProductAttrPics();
        this.$emit('nextStep')
      }
    },

  }
</script>

<style scoped>
.littleMarginLeft {
  margin-left: 10px;
}

.littleMarginTop {
  margin-top: 10px;
}

.paramInput {
  width: 250px;
}

.paramInputLabel {
  display: inline-block;
  width: 100px;
  text-align: right;
  padding-right: 10px
}

.cardBg {
  background: #F8F9FC;
}
.el-button{
  margin-bottom: 1px !important;
  margin-top: 5px !important;
  margin-left: 0px !important;
}
</style>
